﻿#include "multilistpushbutton.h"
#include <QDebug>

MultiListPushButton::MultiListPushButton(QWidget *parent) : QPushButton(parent)
{
    currentMenuIndex = 0;

    setContextMenuPolicy(Qt::CustomContextMenu);
    connect(this, &QPushButton::clicked, this, &MultiListPushButton::showMenu);
}

void MultiListPushButton::setCurrentMenuIndex(int currentMenuIndex){
    this->currentMenuIndex = currentMenuIndex;
}

int MultiListPushButton::getCurrentMenuIndex(){
    return currentMenuIndex;
}

void MultiListPushButton::showMenu(){
    menus[currentMenuIndex]->exec(QCursor::pos());
}

void MultiListPushButton::addMenuItemsLabel(QStringList labels){
    QList<QAction*> actions;
    QMenu *menu = new QMenu();
    for(int i=0;i<labels.size();i++){
        QAction *action = new QAction(labels[i], this);
        action->setCheckable(true);

        connect(action, &QAction::triggered,
                [=]()
        {
            emit this->menuItemClicked(i, action->isChecked());
        });

        actions.append(action);
        menu->addAction(action);
    }
    menus.append(menu);
    menuActions.append(actions);
}

int MultiListPushButton::getMenuSize(int index){
    if(index>=menus.size() || index<0){
        return -1;
    }
    return menuActions[index].size();
}

void MultiListPushButton::setCheckedState(QList<QList<bool>> checkedStateList){
    if(checkedStateList.size()!=menuActions.size()){
        qDebug()<<"Wrong checkStateList size!";
        return;
    }
    for(int i=0;i<checkedStateList.size();i++){
        QList<bool> checkedState = checkedStateList[i];
        QList<QAction*> actions = menuActions[i];
        if(checkedState.size()!=actions.size()){
            qDebug()<<"Wrong checkState size at index "<<i<<"!";
            return;
        }
        for(int j=0;j<checkedState.size();j++){
            actions[j]->setChecked(checkedState[j]);
        }
    }
}
